<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>发送消息</title>
	<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0">
	<script src="__PUBLIC__/News/js/jweixin-1.1.0.js"></script>
	<script src="__PUBLIC__/News/js/jquery.js"></script>
	<!--
	<script src="__PUBLIC__/Common/js/vconsole.min.js"></script>
	-->
	<link rel="stylesheet" href="__PUBLIC__/News/css/example.css"/>
	<link rel="stylesheet" href="__PUBLIC__/News/css/weui.min.css"/>
	<style type="text/css">
		.dep{
			border:1px solid white;
			border-radius: 4px;
			font-size: 12px;
			padding:4px;
			color:gray;
			text-align: center;
			position: relative;
			margin:6px auto;
		}

		.member{
			font-size: 10px;
			padding:4px;
			color:gray;
			display: block;
			float: left;
			margin:3px;
			text-align: center;
			position: relative;
		}
		.member img{
			width: 30px;
			height: 30px;
		}
	</style>
	<script>
		wx.config({
			//关闭调试模式
		    debug: false,
		    appId: '<?php echo $signPackage["appId"];?>',
		    timestamp: <?php echo $signPackage["timestamp"];?>,
		    nonceStr: '<?php echo $signPackage["nonceStr"];?>',
		    signature: '<?php echo $signPackage["signature"];?>',
		    jsApiList: [
		      'closeWindow','openEnterpriseContact','hideOptionMenu'
		    ]
	    });
	    var all_user_list = <?php echo $all_user_list?>;
	    wx.ready(function(){
 			//屏蔽菜单
 			wx.hideOptionMenu();
		});
		function close_window(){
			wx.closeWindow();
		}
		//执行初始化操作
		$(function(){
		});
	</script>
</head>
<body>
	<!-- <div style="text-align: center;padding:3%;">
		<i class="weui-icon-warn"></i>
		该功能暂维护中,请稍候再试...	
	</div> -->



	<!--弹窗提示区域开始-->
	<div style="display: none;" id="notice_msg">
	    <div class="weui-mask"></div>
	    <div class="weui-dialog">
	        <div class="weui-dialog__hd"><strong class="weui-dialog__title">温馨提示</strong></div>
	        <div class="weui-dialog__bd" id="msg_content">您还没有选择消息接收人</div>
	        <div class="weui-dialog__ft">
	            <a href="javascript:;" id="notice_msg_but" class="weui-dialog__btn weui-dialog__btn_primary">确定</a>
	        </div>
	    </div>
	</div>
	<!--确认发送消息弹层开始-->
	<div class="js_dialog" id="confirm_send_msg" style="display: none;">
        <div class="weui-mask"></div>
        <div class="weui-dialog">
            <div class="weui-dialog__hd"><strong class="weui-dialog__title">确认操作</strong></div>
            <div class="weui-dialog__bd">确定发送此消息吗?</div>
            <div class="weui-dialog__ft">
                <a href="javascript:;" class="weui-dialog__btn weui-dialog__btn_default no_send">我再看看</a>
                <a href="javascript:;" class="weui-dialog__btn weui-dialog__btn_primary yes_send">是的</a>
            </div>
        </div>
    </div>
    <!--确认发送消息弹层结束-->

	<!--消息主体区域开始-->
	<div id="main">
		<div class="weui-cells__title">消息标题(长度1-40字符)</div>
		<div class="weui-cells">
		    <div class="weui-cell">
		        <div class="weui-cell__bd">
		            <input class="weui-input" name="title" type="text" placeholder="请输入标题"/>
		        </div>
		    </div>
		</div>
		<div class="weui-cells__title">消息正文(长度1-500字符)</div>
		<div class="weui-cells weui-cells_form">
		    <div class="weui-cell">
		        <div class="weui-cell__bd">
		            <textarea class="weui-textarea" name="content" placeholder="请输入正文" rows="6"></textarea>
		            <div class="weui-textarea-counter"><span id="word_count">0</span>/500</div>
		        </div>
		    </div>
		</div>
		<div id="user_list" class="weui-btn-area">
		<!-- 成员数据回显开始 -->
		<!-- 成员数据回显结束 -->
		</div>
		<div style="clear: both;"></div>
		<div class="weui-btn-area">
			<a class="weui-btn weui-btn_primary" href="javascript:" id="choosePerson">打开通讯录选人</a>
			<a href="javascript:;"  id="showTooltips"  class="weui-btn weui-btn_warn">确定发送</a>
		    <a href="javascript:;" id="close_win" class="weui-btn weui-btn_disabled weui-btn_default">关闭</a>
		</div>
	</div>
	<form action="__CONTROLLER__/sendMessage/state/{$corpid}" method="post">
		<input type="hidden" name="title"/>	
		<input type="hidden" name="content"/>
		<input type="hidden" name="person_list"/>
		<input type="hidden" name="dep_list"/>
		<input type="hidden" name="person_type"/>
		<input type="hidden" name="userid"/>	
	</form>
	<div class="weui-footer" style="margin-top:12%;">
        <p class="weui-footer__links">
            <a href="javascript:void(0);" class="weui-footer__link">中国航天 | 神舟软件</a>
        </p>
        <p class="weui-footer__text">Copyright &copy; 2003-2017</p>
    </div>
</body>
	<script>
	 	//全局初始化变量区域
	 	//成员userid
	 	var userid = '<?php echo $userid;?>';
        //初始化通讯录成员类型状态
        var choose_status = 1;

        //通讯录状态记录
        var book_state = true;
        var selectedUserIds = [];
        var selectedDepartmentIds = [];

		var evalWXjsApi = function(jsApiFun) {
		    if(typeof WeixinJSBridge == "object" && typeof WeixinJSBridge.invoke == "function") {
		        jsApiFun();
		    }else{
		        document.attachEvent && document.attachEvent("WeixinJSBridgeReady", jsApiFun);
		        document.addEventListener && document.addEventListener("WeixinJSBridgeReady", jsApiFun);
		    }
		}
		
		//开启通讯录
		$('#choosePerson').bind('click',function(){
			//执行检测是否录入内容
			//检测标题
			var title = $('input[name=title]').val(); 
			//检测正文
			var content = $('textarea[name=content]').val();
			if(title=='' || content==''){
				$('#msg_content').html('消息标题及正文不能为空哦!');
				$('#notice_msg').show();
				return false;
			}
			openContact();
		});
		function openContact() {
			//检测接口可用性
			wx.checkJsApi({
			      jsApiList: [
			        'openEnterpriseContact',
			      ],
			      success: function (res) {
			      }
			});
		    evalWXjsApi(function() {
		        WeixinJSBridge.invoke("openEnterpriseContact", {
		            "groupId": "{$groupId}",      //管理组权限验证步骤1返回的group_id
		            "timestamp": "{$timestamp}",  //管理组权限验证步骤2使用的时间戳
		            "nonceStr": "{$nonceStr}",    //管理组权限验证步骤2使用的随机字符串
		            "signature": "{$signature}",  //管理组权限验证步骤2生成的签名
		            "params" : {
		            	//非必填，可选部门ID列表（如果ID为0，表示可选管理组权限下所有部门）
		                'departmentIds' : [1,<?php echo $department;?>],
		                //非必填，可选标签ID列表（如果ID为0，表示可选所有标签）
		                'tagIds' : [0],
		                //非必填，可选用户ID列表
		                'userIds' : [],
		                //必填，选择模式，single表示单选，multi表示多选         
		                'mode' : 'multi',
		                //必填，选择限制类型，指定department、tag、user中的一个或者多个
		                'type' : ['department','user'],
		                //非必填，已选部门ID列表
		                'selectedDepartmentIds' : selectedDepartmentIds, 
		                //非必填，已选标签ID列表           
		                'selectedTagIds' : [],
		                //非必填，已选用户ID列表               
		                'selectedUserIds' : selectedUserIds,                  
		            },
		        },function(res) {
		            if (res.err_msg.indexOf('function_not_exist') > -1) {
		                alert('您的微信版本过低请先升级哦!');
		            }else if (res.err_msg.indexOf('openEnterpriseContact:fail') > -1) {
		            	alert(res.err_msg);
		            	alert('哎呀!接口发生异常!');
		                return;
		            }
		            var result = JSON.parse(res.result);

		            //初始化数据
		            $('#user_list').html();

		            var selectAll = result.selectAll;
		            if (!selectAll){
		            	//非全选情况
		            	//已选的部门列表
		                var selectedDepartmentList = result.departmentList;
		                var dep_html = ''; 
		                for (var i = 0; i < selectedDepartmentList.length; i++) {
		                    var department = selectedDepartmentList[i];
		                    //已选的单个部门ID
		                    var departmentId = department.id;   
		                    selectedDepartmentIds[i] = departmentId;
		                    //已选的单个部门名称
		                    var departemntName = department.name;
		                    dep_html += "<div class='dep'>"+departemntName+"<i style='border-radius: 20px; position: absolute;top: -.6em;right: -.4em;'><img class='dep_photo' depid='"+departmentId+"' src='__PUBLIC__/News/img/remove.png' style='width:19px;height:19px;'/></i></div>";
		                }
		                //追加部门
		                $('#user_list').html(dep_html);
		                //已选的标签列表
		                var selectedTagList = result.tagList;    
		                for (var i = 0; i < selectedTagList.length; i++) {
		                    var tag = selectedTagList[i];
		                    //已选的单个标签ID
		                    var tagId = tag.id;
		                    //已选的单个标签名称                
		                    var tagName = tag.name;                
		                }
		                //已选的成员列表
		                var selectedUserList = result.userList;
		                //初始化成员html
		                var member_html = ''; 
		                for(var i=0;i<selectedUserList.length; i++){
		                    var user = selectedUserList[i];
		                    //已选的单个成员ID
		                    var userId = user.id;
		                    selectedUserIds[i] = userId;
		                    //获取成员头像数据
		                    var image = getImage(userId);
		                    //已选的单个成员名称               
		                    var userName = user.name;
		                    userName = userName.substr(0,3);
		                    //生成成员节点
		                    member_html += "<span class='member'><img src='"+image+"'/><br/>"+userName+"<i style='border-radius: 20px; position: absolute;top: -.4em;right: -.4em;'><img class='member_photo' userid='"+userId+"' src='__PUBLIC__/News/img/remove.png' style='width:19px;height:19px;'/></i></span>";
		                }
		                //写入到mem_list div
		                $('#user_list').html($('#user_list').html()+member_html);

		                //监听点击移除成员
						$('.member_photo').bind('click',function(){
							var userid = $(this).attr('userid');
							//移除通讯录成员
							removeMember(userid,$(this));
							$(this).parent().parent().remove();
						});

						//监听点击移除部门
						$('.dep_photo').bind('click',function(){
							var depid = $(this).attr('depid');
							//移除通讯录成员
							removeDep(depid,$(this));
							$(this).parent().parent().remove();
						});
		                book_state = true;
		            }else{
		            	//全选情况
		            	book_state = false;
		            	choose_status = 2;
		            	$('#user_list').html('<div style="text-align:center;"><i class="weui-icon-success"></i>当前已选中全部成员!</div>');
		            }
		            //更改通讯录按钮文字
		            $('#choosePerson').html(' + 继续添加成员');
		        })
		    });
		}

		$('#notice_msg_but').bind('click',function(){
			$('#notice_msg').hide();
		});
		//关闭窗口事件监听
		$('#close_win').bind('click',close_window);
		//监听发送消息按钮
		$('#showTooltips').bind('click',function(){
			//检测是否选人
			if(selectedUserIds.length==0 && selectedDepartmentIds.length==0 && choose_status==1 ){
				$('#msg_content').html('您还没有选择消息接收人呢！');
				$('#notice_msg').show();
				return false;
			};
			
			//检测标题
			var title = $('input[name=title]').val(); 
			//检测正文
			var content = $('textarea[name=content]').val();
			if(title=='' || content==''){
				$('#msg_content').html('消息标题及正文必填哦!');
				$('#notice_msg').show();
				return false;
			}
			//检测标题文字长度是否超标
			if(title.length>40){
				$('#msg_content').html('消息标题最多40个字符!');
				$('#notice_msg').show();
				return false;
			}
			//检测正文文字数量是否超标
			if(content.length>500){
				$('#msg_content').html('消息正文最多500个字符!');
				$('#notice_msg').show();
				return false;
			}
			//整理消息信息
			$('input[name=title]').val(title.trim());
			$('input[name=content]').val(content.trim());
			//消息发起人
			$('input[name=userid]').val(userid);
			//接受成员列表
			$('input[name=person_list]').val(selectedUserIds.join(','));
			$('input[name=dep_list]').val(selectedDepartmentIds.join(','));

			if(choose_status==1){
				$('input[name=person_type]').val(1);
			}else{
				$('input[name=person_type]').val(2);
			}
			//弹出确认操作提示
			$('#confirm_send_msg').show();
		});
		
		//确认发送消息
		$('.yes_send').bind('click',function(){
			$('form').submit();
			$('#confirm_send_msg').css('display','none');
		});
		
		//取消发送消息
		$('.no_send').bind('click',function(){
			$('#confirm_send_msg').css('display','none');
		});
		
		//文本统计
		$('textarea[name=content]').bind('input',function(){
			var len = $(this).val().length;
			$('#word_count').html(500 - len);
		});

		/** 获取成员头像数据 */
		function getImage(userid){
			for(var i in all_user_list){
				if(all_user_list[i].userid==userid){
					return all_user_list[i].avatar;
				}
			}
		}

		/** 删除成员数组中成员 */
		function removeMember(userid){
			var buf = [];
			for(var i=0;i<selectedUserIds.length;i++){
				if(selectedUserIds[i]!=userid){
					buf.push(selectedUserIds[i]);
				}
			}
			selectedUserIds = buf;
			//检测当前是还有成员或者部门
			if(selectedUserIds==0 && selectedDepartmentIds.length==0){
				$('#choosePerson').html('打开通讯录选人');
			}
		}

		/** 删除部门 */
		function removeDep(depid){
			var buf = [];
			for(var i=0;i<selectedDepartmentIds.length;i++){
				if(selectedDepartmentIds[i]!=depid){
					buf.push(selectedDepartmentIds[i]);
				}
			}
			selectedDepartmentIds = buf;
			//检测当前是还有成员或者部门
			if(selectedUserIds==0 && selectedDepartmentIds.length==0){
				$('#choosePerson').html('打开通讯录选人');
			}
		}
	</script>
</html>
